{{define "content"}}
<div x-data="profileManager()" x-init="init()">
    <!-- 页面标题 -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-900">个人资料</h1>
        <p class="text-gray-600">查看和管理您的个人信息</p>
    </div>

    <!-- 加载状态 -->
    <div x-show="isLoading" class="text-center py-12">
        <svg class="w-8 h-8 text-blue-500 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
        </svg>
        <p class="mt-2 text-gray-600">加载个人资料...</p>
    </div>

    <!-- 个人资料内容 -->
    <div x-show="!isLoading" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 个人信息卡片 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">个人信息</h3>
            </div>
            <div class="p-6">
                <div class="flex items-center justify-center mb-6">
                    <div class="w-24 h-24 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 text-3xl font-bold" x-text="getUserInitials()"></div>
                </div>
                
                <div class="text-center mb-6">
                    <h4 class="text-xl font-medium text-gray-900" x-text="profile.real_name"></h4>
                    <p class="text-gray-500" x-text="profile.username"></p>
                    <div class="mt-2">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            <span class="w-2 h-2 rounded-full bg-green-500 mr-1"></span>
                            活跃
                        </span>
                    </div>
                </div>
                
                <div class="space-y-4">
                    <div class="flex items-center">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                        </svg>
                        <span class="text-gray-600 ml-2" x-text="profile.email || '未设置'"></span>
                    </div>
                    <div class="flex items-center">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>
                        </svg>
                        <span class="text-gray-600 ml-2" x-text="profile.phone || '未设置'"></span>
                    </div>
                    <div class="flex items-center">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                        </svg>
                        <span class="text-gray-600 ml-2">创建于 <span x-text="formatDate(profile.created_at)"></span></span>
                    </div>
                    <div class="flex items-center">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                        <span class="text-gray-600 ml-2">上次登录 <span x-text="profile.last_login_at ? formatDate(profile.last_login_at) : '从未登录'"></span></span>
                    </div>
                </div>
                
                <div class="mt-6">
                    <button @click="openEditProfileModal()" class="w-full flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                        </svg>
                        编辑个人资料
                    </button>
                </div>
            </div>
        </div>

        <!-- 角色信息卡片 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">角色与权限</h3>
            </div>
            <div class="p-6">
                <div x-show="userRoles.length === 0" class="text-center py-8 text-gray-500">
                    <svg class="w-12 h-12 text-gray-300 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                    </svg>
                    <p>您未被分配任何角色</p>
                </div>
                
                <div x-show="userRoles.length > 0" class="space-y-4">
                    <template x-for="role in userRoles" :key="role.id">
                        <div class="border border-gray-200 rounded-lg p-4">
                            <div class="flex items-center">
                                <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <h4 class="text-md font-medium text-gray-900" x-text="role.display_name"></h4>
                                    <p class="text-sm text-gray-500" x-text="role.description || '无描述'"></p>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- 安全设置卡片 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">安全设置</h3>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <h4 class="text-md font-medium text-gray-900">密码</h4>
                            <p class="text-sm text-gray-500">上次更新: <span x-text="profile.password_updated_at ? formatDate(profile.password_updated_at) : '未知'"></span></p>
                        </div>
                        <button @click="openChangePasswordModal()" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                            修改
                        </button>
                    </div>
                    
                    <div class="border-t border-gray-200 pt-4">
                        <h4 class="text-md font-medium text-gray-900 mb-2">最近登录</h4>
                        <div x-show="loginHistory.length === 0" class="text-center py-4 text-gray-500">
                            <p>暂无登录记录</p>
                        </div>
                        
                        <div x-show="loginHistory.length > 0" class="space-y-3">
                            <template x-for="(record, index) in loginHistory" :key="index">
                                <div class="flex items-start">
                                    <div class="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center text-green-600 mt-1">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"></path>
                                        </svg>
                                    </div>
                                    <div class="ml-3">
                                        <p class="text-sm text-gray-900" x-text="formatDateTime(record.login_time)"></p>
                                        <div class="flex items-center text-xs text-gray-500 mt-1">
                                            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9v-9m0-9a9 9 0 00-9 9m9-9v9"></path>
                                            </svg>
                                            <span x-text="record.ip_address || '未知IP'"></span>
                                        </div>
                                        <div class="flex items-center text-xs text-gray-500 mt-1">
                                            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                            </svg>
                                            <span x-text="record.user_agent || '未知设备'"></span>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑个人资料模态框 -->
    <div x-show="showEditProfileModal" class="fixed inset-0 overflow-y-auto z-50" style="display: none;">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">编辑个人资料</h3>
                </div>
                
                <form @submit.prevent="updateProfile()" class="p-6">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">用户名</label>
                            <input type="text" 
                                   x-model="editForm.username" 
                                   disabled
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 bg-gray-100">
                            <p class="mt-1 text-sm text-gray-500">用户名不可修改</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">真实姓名 <span class="text-red-500">*</span></label>
                            <input type="text" 
                                   x-model="editForm.real_name" 
                                   required 
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">手机号</label>
                            <input type="tel" 
                                   x-model="editForm.phone" 
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">邮箱</label>
                            <input type="email" 
                                   x-model="editForm.email" 
                                   @blur="checkEmail()"
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                            <p x-show="errors.email" class="mt-1 text-sm text-red-600" x-text="errors.email"></p>
                        </div>
                    </div>
                    
                    <div class="mt-6 flex justify-end space-x-3">
                        <button type="button" 
                                @click="closeEditProfileModal()"
                                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                            取消
                        </button>
                        <button type="submit" 
                                :disabled="isSubmitting"
                                class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50">
                            <span x-show="isSubmitting">
                                <svg class="w-4 h-4 mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>处理中...
                            </span>
                            <span x-show="!isSubmitting">保存修改</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 修改密码模态框 -->
    <div x-show="showChangePasswordModal" class="fixed inset-0 overflow-y-auto z-50" style="display: none;">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">修改密码</h3>
                </div>
                
                <form @submit.prevent="changePassword()" class="p-6">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">当前密码 <span class="text-red-500">*</span></label>
                            <input type="password" 
                                   x-model="passwordForm.old_password" 
                                   required 
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">新密码 <span class="text-red-500">*</span></label>
                            <input type="password" 
                                   x-model="passwordForm.new_password" 
                                   required 
                                   minlength="6"
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                            <p class="mt-1 text-sm text-gray-500">密码长度至少6位</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">确认新密码 <span class="text-red-500">*</span></label>
                            <input type="password" 
                                   x-model="passwordForm.confirm_password" 
                                   required 
                                   minlength="6"
                                   class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                            <p x-show="errors.confirm_password" class="mt-1 text-sm text-red-600" x-text="errors.confirm_password"></p>
                        </div>
                    </div>
                    
                    <div class="mt-6 flex justify-end space-x-3">
                        <button type="button" 
                                @click="closeChangePasswordModal()"
                                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                            取消
                        </button>
                        <button type="submit" 
                                :disabled="isSubmitting"
                                class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50">
                            <span x-show="isSubmitting">
                                <svg class="w-4 h-4 mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>处理中...
                            </span>
                            <span x-show="!isSubmitting">修改密码</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function profileManager() {
    return {
        // 数据
        profile: {},
        userRoles: [],
        loginHistory: [],
        
        // 编辑表单
        editForm: {
            username: '',
            real_name: '',
            phone: '',
            email: ''
        },
        
        // 密码表单
        passwordForm: {
            old_password: '',
            new_password: '',
            confirm_password: ''
        },
        
        // 错误信息
        errors: {
            email: '',
            confirm_password: ''
        },
        
        // 状态
        isLoading: true,
        isSubmitting: false,
        showEditProfileModal: false,
        showChangePasswordModal: false,
        
        // 初始化
        async init() {
            // 并行加载数据
            await Promise.all([
                this.loadProfile(),
                this.loadUserRoles(),
                this.loadLoginHistory()
            ]);
            
            this.isLoading = false;
        },
        
        // 加载个人资料
        async loadProfile() {
            try {
                const response = await fetch('/api/v1/profile');
                const result = await response.json();
                
                if (result.success && result.data) {
                    this.profile = result.data;
                } else {
                    this.showToast('加载个人资料失败: ' + (result.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('加载个人资料失败:', error);
                this.showToast('加载个人资料失败', 'error');
            }
        },
        
        // 加载用户角色
        async loadUserRoles() {
            try {
                const response = await fetch('/api/v1/profile/roles');
                const result = await response.json();
                
                if (result.success) {
                    this.userRoles = result.data || [];
                } else {
                    console.error('加载角色信息失败:', result.message);
                }
            } catch (error) {
                console.error('加载角色信息失败:', error);
            }
        },
        
        // 加载登录历史
        async loadLoginHistory() {
            try {
                const response = await fetch('/api/v1/profile/login-history?limit=3');
                const result = await response.json();
                
                if (result.success) {
                    this.loginHistory = result.data || [];
                } else {
                    console.error('加载登录历史失败:', result.message);
                }
            } catch (error) {
                console.error('加载登录历史失败:', error);
            }
        },
        
        // 打开编辑个人资料模态框
        openEditProfileModal() {
            this.editForm = {
                username: this.profile.username,
                real_name: this.profile.real_name,
                phone: this.profile.phone || '',
                email: this.profile.email || ''
            };
            
            this.errors.email = '';
            this.showEditProfileModal = true;
        },
        
        // 关闭编辑个人资料模态框
        closeEditProfileModal() {
            this.showEditProfileModal = false;
        },
        
        // 打开修改密码模态框
        openChangePasswordModal() {
            this.passwordForm = {
                old_password: '',
                new_password: '',
                confirm_password: ''
            };
            
            this.errors.confirm_password = '';
            this.showChangePasswordModal = true;
        },
        
        // 关闭修改密码模态框
        closeChangePasswordModal() {
            this.showChangePasswordModal = false;
        },
        
        // 检查邮箱是否存在
        async checkEmail() {
            if (!this.editForm.email || this.editForm.email === this.profile.email) {
                this.errors.email = '';
                return;
            }
            
            try {
                const response = await fetch(`/api/v1/users/check-email?email=${encodeURIComponent(this.editForm.email)}&exclude_id=${this.profile.id}`);
                const result = await response.json();
                
                if (result.data && result.data.exists) {
                    this.errors.email = '该邮箱已被其他用户使用';
                } else {
                    this.errors.email = '';
                }
            } catch (error) {
                console.error('检查邮箱失败:', error);
            }
        },
        
        // 更新个人资料
        async updateProfile() {
            if (this.errors.email) return;
            
            this.isSubmitting = true;
            
            try {
                const response = await fetch('/api/v1/profile', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        real_name: this.editForm.real_name,
                        phone: this.editForm.phone,
                        email: this.editForm.email
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    this.showToast('个人资料更新成功', 'success');
                    this.closeEditProfileModal();
                    await this.loadProfile();
                } else {
                    this.showToast(result.message || '更新失败', 'error');
                }
            } catch (error) {
                console.error('更新个人资料失败:', error);
                this.showToast('更新个人资料失败', 'error');
            } finally {
                this.isSubmitting = false;
            }
        },
        
        // 验证密码表单
        validatePasswordForm() {
            let isValid = true;
            
            // 检查密码确认
            if (this.passwordForm.new_password !== this.passwordForm.confirm_password) {
                this.errors.confirm_password = '两次输入的密码不一致';
                isValid = false;
            } else {
                this.errors.confirm_password = '';
            }
            
            return isValid;
        },
        
        // 修改密码
        async changePassword() {
            if (!this.validatePasswordForm()) return;
            
            this.isSubmitting = true;
            
            try {
                const response = await fetch('/api/v1/profile/password', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        old_password: this.passwordForm.old_password,
                        new_password: this.passwordForm.new_password
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    this.showToast('密码修改成功', 'success');
                    this.closeChangePasswordModal();
                    await this.loadProfile();
                } else {
                    this.showToast(result.message || '密码修改失败', 'error');
                }
            } catch (error) {
                console.error('修改密码失败:', error);
                this.showToast('修改密码失败', 'error');
            } finally {
                this.isSubmitting = false;
            }
        },
        
        // 获取用户名首字母
        getUserInitials() {
            if (!this.profile.real_name) return '';
            
            return this.profile.real_name.charAt(0).toUpperCase();
        },
        
        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });
        },
        
        // 格式化日期时间
        formatDateTime(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        },
        
        // 显示提示消息
        showToast(message, type = 'info') {
            // 这里可以集成一个 toast 组件
            console.log(`${type}: ${message}`);
            alert(message);
        }
    };
}
</script>
{{end}}